<template>
  <el-container style="padding: 40px; max-width: 1200px; margin: 0 auto;">
    <el-main>
      <el-card style="padding: 32px; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
        <h2 style="text-align:center; font-size: 26px; margin-bottom: 24px;">成绩管理后台</h2>
        <el-table
          :data="tableData"
          style="width: 100%;"
          v-loading="loading"
          empty-text="暂无成绩数据"
          height="600"
        >
          <el-table-column prop="name" label="姓名" width="180" />
          <el-table-column prop="score" label="成绩" width="120" />
          <el-table-column label="是否合格" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.score >= 60 ? 'success' : 'danger'">
                {{ scope.row.score >= 60 ? '合格' : '不合格' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="做题时长" width="140">
            <template #default="scope">
              {{ formatDuration(scope.row.duration) }}
            </template>
          </el-table-column>
          <el-table-column prop="exam_date" label="考试时间" width="200">
            <template #default="scope">
              {{ formatTime(scope.row.exam_date) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const tableData = ref([])
const loading = ref(false)

const formatDuration = (seconds) => {
  if (!seconds && seconds !== 0) return '—'
  const m = String(Math.floor(seconds / 60)).padStart(2, '0')
  const s = String(seconds % 60).padStart(2, '0')
  return `${m}:${s}`
}
const formatTime = (t) => {
  if (!t) return '—'
  const d = new Date(t)
  if (isNaN(d.getTime())) return t
  return d.toLocaleString()
}

const fetchScores = async () => {
  loading.value = true
  try {
    const res = await fetch('http://localhost:3000/api/admin/user-scores')
    const data = await res.json()
    if (res.ok) {
      tableData.value = data.data || []
    } else {
      ElMessage.error(data.message || '获取成绩失败')
    }
  } catch (e) {
    ElMessage.error('网络请求失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchScores()
})
</script>

<style scoped>
h2 {
  font-weight: bold;
}
</style>
  